package com.mooc.tree.bak.BinTree.exerice;

import com.mooc.tree.bak.BinTree.BinTreeNode;
import com.mooc.tree.bak.BinTree.BinaryTree;

/**
 * @Author zhang.xin
 * @Description: 求一个树的高度（树结构同前）
 * @Date 2019/12/24
 */
public class GetHeight {

    /**
     * 分别遍历左子树和右子树，取最大值
     * @param root
     * @return
     */
    public int getTreeHeiht(BinTreeNode root) {
        int leftHeight;
        int rightHeight;
        int height;
        if (root != null) {
            leftHeight = getTreeHeiht(root.getLeft());
            rightHeight = getTreeHeiht(root.getRight());
            height = leftHeight > rightHeight ? leftHeight : rightHeight;
            return height + 1;
        }
        return 0;
    }

    // 测试
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        BinTreeNode root = tree.createBinaryTree();
        GetHeight height = new GetHeight();
        int h = height.getTreeHeiht(root);
        System.out.println(h); // 4
    }

}
